package cn.security.auth.config;

import cn.security.auth.filter.AuthenticationFilter;
import cn.security.auth.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;
@Order(5)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    @Autowired
    private AuthenticationFilter authenticationFilter;

    @Autowired
    @Qualifier("customUserDetailServiceImpl")
    private UserDetailsService userDetailsService;

    @Autowired
    private LoginService loginService;

    @Value("${custom.security.exclude.urls}")
    private String[] excludePaths;
    /**
     * 注册时需要使用该加密方式
     * 自定义密码加密方式 BCryptPasswordEncoder
     * SHA-256 + 随机盐 + 密钥对密码进行加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 获取AuthenticationManager
     * 用来自定义认证用户
     * @return
     * @throws Exception
     */
    @Bean(name="customAuthenticationManagerConfig")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        CustomAuthenticationManagerConfig customAuthenticationManagerConfig=new CustomAuthenticationManagerConfig();
        customAuthenticationManagerConfig.setLoginService(loginService);
        return customAuthenticationManagerConfig;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭csrf
                .csrf().disable()
                // 关闭basic认证(弹窗)
                .httpBasic().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(excludePaths).anonymous()
                // 除上面外的所有请求都需要鉴权认证
                .anyRequest().authenticated().
                and()
                .headers().frameOptions().disable()
                .and()
                .cors();

        // 处理授权失败403
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
        http.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略URL,classpath:/META-INF/resources/**,/swagger-resources/**,/v2/api-docs/**
        web.ignoring().antMatchers(excludePaths);
    }


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowedHeaders(Collections.singletonList(CorsConfiguration.ALL));
        configuration.setAllowedMethods(Arrays.asList("GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "TRACE"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}
